// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl.NavSellOrderLogisticsServiceImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.fowo.api.datainterface.service.impl.DatainterfaceServiceImpl;
import com.fowo.api.datainterface.util.JsonUtil;
import com.fowo.api.model.nav.sell.order.NavSellOrderVo;
import com.fowo.api.model.nav.sell.order.SubmitOrderParam;
import com.fowo.api.model.nav.sell.order.SubmitOrderResult;
import com.fowo.api.model.nav.sell.order.declare.NavSellOrderDeclareItemVo;
import com.fowo.api.service.NavSellOrderLogisticsService;
import com.fowo.api.service.impl.NavLogisticsChannelServiceImpl;
import com.fowo.api.service.impl.ShopInfoServiceImpl;
import com.fowo.api.service.impl.SysCountryServiceImpl;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单管理 服务实现类
 *
 * @author 蜂窝蜜造平台 配置人：任凯
 */
@Service
@Slf4j
@DS("ds24")
public class NavSellOrderEboLogisticsServiceImpl implements NavSellOrderLogisticsService {

    @Resource
    private DatainterfaceServiceImpl datainterfaceService;
    //接口
    private static final String SUBMITORDER = "EC00491";


    public String getType() {
        return "EBO";
    }

    /**
     * 物流下单
     *
     * @param navSellOrderVo
     */
    public SubmitOrderResult submitLogisticsOrder(NavSellOrderVo navSellOrderVo) {
        String trackingNumber = ObjUtil.defaultIfNull(navSellOrderVo.getOrderId(), "");
        SubmitOrderParam order = new SubmitOrderParam();
        SubmitOrderParam.Order orderJson = new SubmitOrderParam().new Order();
        SubmitOrderResult submitOrderResult = new SubmitOrderResult();
        submitOrderResult.setSuccess(false);
        submitOrderResult.setCode(500);
        try {
            Assert.isTrue(ObjUtil.isNotEmpty(navSellOrderVo), "物流参数异常!");
            String expressName = SpringUtil.getBean(NavLogisticsChannelServiceImpl.class).getExpressNameById(navSellOrderVo.getDeliveryLogisticsChannel());
            String country = SpringUtil.getBean(SysCountryServiceImpl.class).getCountryById(navSellOrderVo.getDeliveryCountry());
            List<NavSellOrderDeclareItemVo> declareItemVoList = navSellOrderVo.getDeclare();
            Assert.isTrue(CollUtil.isNotEmpty(declareItemVoList), "报关信息不存在!");
            orderJson.setExpressName(expressName);
            orderJson.setWeight(Convert.toInt(NumberUtil.add(declareItemVoList.stream().map(NavSellOrderDeclareItemVo::getPackingWeight).toArray(BigDecimal[]::new)), 0));
            orderJson.setCountry(ObjUtil.defaultIfNull(country, ""));
            orderJson.setProvince(ObjUtil.defaultIfNull(navSellOrderVo.getDeliveryProvince(), ""));
            orderJson.setCity(ObjUtil.defaultIfNull(navSellOrderVo.getDeliveryCity(), ""));
            orderJson.setAddressLine1(ObjUtil.defaultIfNull(navSellOrderVo.getDeliveryAddress1(), ""));
            orderJson.setAddressLine2(ObjUtil.defaultIfNull(navSellOrderVo.getDeliveryAddress2(), ""));
            orderJson.setBuyer(ObjUtil.defaultIfNull(navSellOrderVo.getDeliveryReceipt(), ""));
            orderJson.setTaxNumber(ObjUtil.defaultIfNull(navSellOrderVo.getDeliverySenderTaxNo(), ""));
            orderJson.setIdentityNumber(ObjUtil.defaultIfNull(navSellOrderVo.getDeliveryRecipientIdentityNo(), ""));
            orderJson.setTelephone(ObjUtil.defaultIfNull(navSellOrderVo.getDeliveryPhone(), ""));
            orderJson.setEmail(ObjUtil.defaultIfNull(navSellOrderVo.getBuyerEmail(), ""));
            orderJson.setPostCode(ObjUtil.defaultIfNull(navSellOrderVo.getDeliveryZipCode(), ""));
            orderJson.setTrackingNumber(trackingNumber);
            orderJson.setLength(Convert.toInt(navSellOrderVo.getDeliveryRealSizeLength(), 0));
            orderJson.setWidth(Convert.toInt(navSellOrderVo.getDeliveryRealSizeWidth(), 0));
            orderJson.setHeight(Convert.toInt(navSellOrderVo.getDeliveryRealSizeHeight(), 0));
            orderJson.setQuantity(Convert.toInt(NumberUtil.add(declareItemVoList.stream().map(NavSellOrderDeclareItemVo::getQuantity).toArray(Integer[]::new)), 0));
            String shopName = SpringUtil.getBean(ShopInfoServiceImpl.class).getShopNameById(navSellOrderVo.getShopInfo());
            orderJson.setRemark(ObjUtil.defaultIfNull(shopName, ""));
            orderJson.setIossTaxId(ObjUtil.defaultIfNull(navSellOrderVo.getDeliverySenderTaxNo(), ""));
            orderJson.setCustomOrderId(trackingNumber);
            orderJson.setDoorplate(ObjUtil.defaultIfNull(navSellOrderVo.getDeliveryHouseNumber(), ""));

            List<SubmitOrderParam.Order.OrderItems> orderItemsList = new ArrayList<>();
            for (NavSellOrderDeclareItemVo declareItemVo : declareItemVoList) {
                SubmitOrderParam.Order.OrderItems orderItems = new SubmitOrderParam().new Order().new OrderItems();
                SubmitOrderParam.Order.OrderItems.OrderItemType orderItemType = new SubmitOrderParam().new Order().new OrderItems().new OrderItemType();
                orderItemType.setDeclareNameCn(ObjUtil.defaultIfNull(declareItemVo.getChineseName(), ""));
                orderItemType.setDeclareName(ObjUtil.defaultIfNull(declareItemVo.getEnglishName(), ""));
                orderItemType.setDeclareValue(Convert.toBigDecimal(NumberUtil.mul(declareItemVo.getCustomsCharges(), declareItemVo.getQuantity()), BigDecimal.ZERO));
                orderItemType.setQuantity(Convert.toInt(declareItemVo.getQuantity(), 0));
                orderItemType.setWeight(Convert.toInt(declareItemVo.getPackingWeight(), 0));
                orderItemType.setSku(ObjUtil.defaultIfNull(declareItemVo.getSku(), ""));
                orderItemType.setHsCode(ObjUtil.defaultIfNull(declareItemVo.getCustomsCode(), ""));
                orderItemType.setWebLink("");
                orderItems.setOrderItemType(orderItemType);
                orderItemsList.add(orderItems);
            }
            orderJson.setOrderItemsList(orderItemsList);
            order.setOrder(orderJson);
            Object res = datainterfaceService.executeInterface(null, SUBMITORDER, null, order, null);
            if (ObjUtil.isEmpty(res)) {
                submitOrderResult.setMessage(StrUtil.concat(true, "提交订单数据到EBO物流接口调用失败,详细信息请查看接口中心日志!"));
            } else {
                BeanUtil.copyProperties(JsonUtil.getJsonToBeanSafe(res, SubmitOrderResult.class), submitOrderResult);
                //成功之后获取面单
//                List<SysFile> dataList = this.getFacePDF(submitOrderResult.getOrderId());
//                submitOrderResult.setData(dataList);
            }
        } catch (Exception ex) {
            submitOrderResult.setMessage(StrUtil.concat(true, "接口调用异常,调用参数:", JsonUtil.getObjectToString(orderJson), ",异常信息:", StrUtil.subPre(ExceptionUtil.getRootCauseMessage(ex), 2000)));
        } finally {
            return submitOrderResult;
        }
    }

}